{% extends "base.html" %}

{% block cur_page_nav %}
{{ macros::current_page_nav(toc=section.toc) }}
{% endblock %}

{% block content %}
    <p class="page-title">{{ section.title }}</p>
    {{ section.content | safe }}
{% endblock content %}

{% block prev_link %}
    {# need to find the last page of the previous section or the previous section directly
     if there isn't any pages in it #}
    {% set index = get_section(path="_index.md") %}
    {% set found_current = false %}
    {% for s in index.subsections | reverse %}
        {% set subsection = get_section(path=s) %}
        {% if subsection.permalink == section.permalink %}
            {% set_global found_current = true %}
        {% else %}
            {% if found_current %}
                {% if subsection.pages %}
                    {% set last_page = subsection.pages | last %}
                    {{ macros::nav_prev_item(rel_top=rel_top, title=last_page.title, path=last_page.path) }}
                {% else %}
                    {{ macros::nav_prev_item(rel_top=rel_top, title=subsection.title, path=subsection.path) }}
                {% endif %}
                {# no break #}
                {% set_global found_current = false %}
            {% endif %}
        {% endif %}
    {% endfor %}
{% endblock prev_link %}

{% block next_link %}
    {% if section.pages %}
        {% set next_page = section.pages | first %}
        {{ macros::nav_next_item(rel_top=rel_top, title=next_page.title, path=next_page.path) }}
    {% else %}
        {# No page in the section, find the link for the following section #}
        {% set index = get_section(path="_index.md") %}
        {% if current_path == "/" %}
            {# Is this the root section, and it has no pages? Start at the beginning. #}
            {% set subsection = get_section(path=index.subsections[0]) %}
            {{ macros::nav_next_item(rel_top=rel_top, title=subsection.title, path=subsection.path) }}
        {% else %}
            {% set found_current = false %}
            {% for s in index.subsections %}
                {% set subsection = get_section(path=s) %}
                {% if found_current %}
                    {{ macros::nav_next_item(rel_top=rel_top, title=subsection.title, path=subsection.path) }}
                    {# no break #}
                    {% set_global found_current = false %}
                {% endif %}
                {% if subsection.permalink == section.permalink %}
                    {% set_global found_current = true %}
                {% endif %}
            {% endfor %}
        {% endif %}
    {% endif %}
{% endblock next_link %}
